@echo off
setlocal enabledelayedexpansion
set "hostname=github.com"
set "hostsPath=C:\Windows\System32\drivers\etc\hosts"
set "tempHostsPath=%hostsPath%.tmp"

:: 创建一个临时的hosts文件，用于替换旧的hosts文件
copy "!hostsPath!" "!tempHostsPath!"

:: 删除包含*.github.com的行
for /f "tokens=*" %%a in ('type "!tempHostsPath!" ^| findstr /v /i "*.github.com"') do (
    echo %%a >> "!hostsPath!.new"
)
move /y "!hostsPath!.new" "!tempHostsPath!"

:: 检查IP地址并ping测试
for %%a in (119.29.29.29 180.76.76.76 114.114.114.114 114.114.115.115 223.5.5.5 180.184.1.1 77.88.8.8 8.8.8.8) do (
    for /f "tokens=2 delims=: " %%i in ('nslookup %hostname% %%a 2^>nul ^| findstr "Address"') do (
        set "ip=%%i"
        if not "!ip!"=="%%a" (
            echo Pinging IP: !ip!
            ping -n 1 !ip! >nul && (
                echo Found a working IP: !ip!
                :: 将可用的IP地址写入hosts文件
                echo !ip! *.github.com >> "!tempHostsPath!"
                goto :updateHosts
            )
        )
    )
)

:updateHosts
:: 替换旧的hosts文件
move /y "!tempHostsPath!" "!hostsPath!"

echo Github is connect
echo Done.
pause
endlocal
